#include "InputManager.h"
#include <sstream>
#include "Game.h"
using namespace std;

InputManager::InputManager(void)
{
	m_keyboard = NULL;
	m_mouse = NULL;
}


InputManager::~InputManager(void)
{
	if(m_inputSystem)
	{
		if(m_joysticks.size() > 0)
		{
			m_itJoystick = m_joysticks.begin();
			m_itJoystickEnd = m_joysticks.end();

			for(; m_itJoystick != m_itJoystickEnd; ++m_itJoystick)
			{
				m_inputSystem->destroyInputObject( *m_itJoystick );
			}
			m_joysticks.clear();
		}

		if(m_mouse != NULL)
			m_inputSystem->destroyInputObject(m_mouse);
		if(m_keyboard != NULL)
			m_inputSystem->destroyInputObject(m_keyboard);

		m_inputSystem->destroyInputSystem ( m_inputSystem );
		m_inputSystem = 0;
	}

}

void InputManager::Initialize(HWND wndHandle)
{
	OIS::ParamList paramList;
	size_t windowHnd = 0;
	ostringstream wnd;
	wnd << (size_t)(wndHandle);

	paramList.insert( std::make_pair( std::string("WINDOW"), wnd.str() ) );

	m_inputSystem = OIS::InputManager::createInputSystem( paramList );

	if( m_inputSystem->getNumberOfDevices(OIS::OISJoyStick) > 0)
	{
		m_joysticks.resize( m_inputSystem->getNumberOfDevices(OIS::OISJoyStick) );

		m_itJoystick = m_joysticks.begin();
		m_itJoystickEnd = m_joysticks.end();

		for(; m_itJoystick != m_itJoystickEnd; ++m_itJoystick)
		{
			(*m_itJoystick) = static_cast<OIS::JoyStick*>( m_inputSystem->createInputObject( OIS::OISJoyStick, true ) );
		}

	}

	if( m_inputSystem->getNumberOfDevices(OIS::OISKeyboard) > 0)
		m_keyboard = static_cast<OIS::Keyboard*>(m_inputSystem->createInputObject( OIS::OISKeyboard, true, ""));
	else
		MessageBox(wndHandle, L"Make sure a keyboard is connected", L"Input Error", 0);

	if( m_inputSystem->getNumberOfDevices(OIS::OISMouse) > 0)
		m_mouse = static_cast<OIS::Mouse*>(m_inputSystem->createInputObject( OIS::OISMouse, true, ""));
	else
		MessageBox(wndHandle, L"Make sure a mouse is connected", L"Input Error", 0);


}

void InputManager::Update()
{
	if(m_joysticks.size() > 0)
	{
		m_itJoystick = m_joysticks.begin();
		m_itJoystickEnd = m_joysticks.end();

		for(; m_itJoystick != m_itJoystickEnd; ++m_itJoystick)
		{
			(*m_itJoystick)->capture();
		}
	}
	if(m_keyboard != NULL)
		m_keyboard->capture();

	if(m_mouse != NULL)
		m_mouse->capture();
	
}

bool InputManager::IsButtonDown(int playerIndex, int button)
{
	if(m_joysticks.size() > 0)
	{
		return m_joysticks[playerIndex]->getJoyStickState().mButtons[button];
	}
	else return false;
}

int InputManager::GetSliderValue(int playerIndex, int sliderID)
{
	return 0;
}

int InputManager::GetAxisValue(int playerIndex, int axisID)
{
	return 0;
}

bool InputManager::IsKeyDown(OIS::KeyCode key)
{
	return m_keyboard->isKeyDown(key);
}